package com.github.niefy.modules.third.controller;

import com.github.niefy.common.utils.R;
import com.github.niefy.modules.third.dto.in.ThirdSubMsgIn_001;
import com.github.niefy.modules.third.entity.ThirdUser;
import com.github.niefy.modules.third.service.ThirdUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.subscribe.WxMpSubscribeMessage;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * 二、三方订阅通知转发
 */
@RestController
@RequestMapping("/thirdOpen/subMsg")
@Tag(name = "二、三方订阅通知转发")
@RequiredArgsConstructor
@Slf4j
public class ThirdSubMsgController {

    private final WxMpService wxMpService;
    private final ThirdUserService thirdUserService;

    /*
    *一次性订阅通知转发样例
    * */
    @PostMapping("/send")
    @Operation(summary = "一次性订阅通知发送",description = "")
    public R sendOnceMsg(HttpServletRequest request, HttpServletResponse response, ThirdSubMsgIn_001 in) throws WxErrorException {
        String stuId = in.getStuId();
        ThirdUser thirdUser = thirdUserService.query()
                .eq("third_id", stuId)
                .one();
        if (thirdUser==null){
            return R.error("该用户ID未绑定公众平台");
        }
        wxMpService.switchoverTo(thirdUser.getAppId());
        var stringStringHashMap = new HashMap<String, String>();
        stringStringHashMap.put("thing1","刘喵喵");
        stringStringHashMap.put("thing2","这是个测试信息");
        WxMpSubscribeMessage msg = WxMpSubscribeMessage.builder()
                .toUser(thirdUser.getOpenId())
                .templateId("xpalM_l22wC4jBGy1VYJpshNOc-RzS4YdxK7h4jzw2M")
                .page("http://spmstu.neusoft.edu.cn/spmstu/spm/rpt/spmtermrpt.do")
                .dataMap(stringStringHashMap)
                .build();
        wxMpService.getSubscribeMsgService().send(msg);
        return R.ok();
    }
}
